<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title} + ' - FTP管理系统'">连接管理 - FTP管理系统</title>

    <!-- Bootstrap CSS -->
    <link th:href="@{/webjars/bootstrap/5.3.0/css/bootstrap.min.css}" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://witmore.oss-cn-hangzhou.aliyuncs.com/cdn/npm/font-awesome/6.7.2/all.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link th:href="@{/css/admin.css}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <div class="admin-layout">
            <!-- 左侧边栏 -->
            <div class="sidebar">
                <div class="sidebar-brand">
                    <h4><i class="fas fa-server me-2"></i>FTP管理系统</h4>
                </div>
                <ul class="sidebar-menu">
                    <li>
                        <a href="/admin">
                            <i class="fas fa-tachometer-alt"></i>仪表盘
                        </a>
                    </li>
                    <li>
                        <a href="/admin/users">
                            <i class="fas fa-users"></i>用户管理
                        </a>
                    </li>
                    <li>
                        <a href="/admin/logs">
                            <i class="fas fa-list-alt"></i>操作日志
                        </a>
                    </li>
                    <li>
                        <a href="/admin/connections" class="active">
                            <i class="fas fa-plug"></i>连接管理
                        </a>
                    </li>
                    <li>
                        <a href="/admin/monitor">
                            <i class="fas fa-chart-line"></i>系统监控
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 主内容区域 -->
            <div class="main-content">
                <!-- 顶部导航栏 -->
                <div class="top-navbar">
                    <h1 class="page-title">连接管理</h1>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="/admin">首页</a></li>
                            <li class="breadcrumb-item active">连接管理</li>
                        </ol>
                    </nav>
                </div>

                <!-- 内容区域 -->
                <div class="content-wrapper">
                    <!-- 页面操作按钮 -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div></div>
                        <button class="btn btn-outline-primary" @click="loadConnections">
                            <i class="fas fa-sync-alt me-2"></i>刷新
                        </button>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                                        <input type="text" class="form-control" placeholder="搜索用户名..."
                                               v-model="searchForm.username" @keyup.enter="loadConnections">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <input type="text" class="form-control" placeholder="客户端IP..."
                                           v-model="searchForm.clientIp" @keyup.enter="loadConnections">
                                </div>
                                <div class="col-md-3">
                                    <select class="form-select" v-model="searchForm.status">
                                        <option value="">全部状态</option>
                                        <option value="CONNECTED">已连接</option>
                                        <option value="DISCONNECTED">已断开</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <div class="btn-group w-100">
                                        <button class="btn btn-outline-primary" @click="loadConnections">
                                            <i class="fas fa-search me-1"></i>搜索
                                        </button>
                                        <button class="btn btn-outline-secondary" @click="resetSearch">
                                            <i class="fas fa-undo me-1"></i>重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 连接列表 -->
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>会话ID</th>
                                            <th>用户名</th>
                                            <th>客户端IP</th>
                                            <th>客户端端口</th>
                                            <th>连接时间</th>
                                            <th>断开时间</th>
                                            <th>持续时间</th>
                                            <th>状态</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="conn in connections" :key="conn.id">
                                            <td>
                                                <code>{{ conn.sessionId }}</code>
                                            </td>
                                            <td>
                                                <i class="fas fa-user me-2"></i>{{ conn.username || '-' }}
                                            </td>
                                            <td>
                                                <code>{{ conn.clientIp }}</code>
                                            </td>
                                            <td>{{ conn.clientPort || '-' }}</td>
                                            <td>{{ formatDate(conn.connectTime) }}</td>
                                            <td>{{ formatDate(conn.disconnectTime) }}</td>
                                            <td>
                                                <span v-if="conn.duration" class="badge bg-info">
                                                    {{ formatDuration(conn.duration) }}
                                                </span>
                                                <span v-else class="text-muted">-</span>
                                            </td>
                                            <td>
                                                <span class="badge" :class="getStatusBadgeClass(conn.status)">
                                                    <i :class="getStatusIcon(conn.status)" class="me-1"></i>
                                                    {{ getStatusText(conn.status) }}
                                                </span>
                                            </td>
                                        </tr>
                                        <tr v-if="connections.length === 0">
                                            <td colspan="8" class="text-center text-muted py-4">
                                                <i class="fas fa-inbox fa-2x mb-2"></i><br>
                                                暂无连接记录
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>

                            <!-- 分页组件 -->
                            <div v-if="pagination.total > 0" class="mt-4">
                                <div class="d-flex justify-content-end align-items-center flex-wrap">
                                    <!-- 统计信息 -->
                                    <div class="text-muted small me-4 mb-2">
                                        <i class="fas fa-info-circle me-1"></i>
                                        共 {{ pagination.total }} 条记录
                                    </div>
                                    
                                    <!-- 每页显示选择器 -->
                                    <div class="me-3 mb-2">
                                        <label class="form-label mb-0 me-2 text-muted small">每页显示:</label>
                                        <select class="form-select form-select-sm d-inline-block" 
                                                style="width: auto;" 
                                                v-model="pagination.size" 
                                                @change="changePageSize">
                                            <option value="10">10 条</option>
                                            <option value="20">20 条</option>
                                            <option value="50">50 条</option>
                                            <option value="100">100 条</option>
                                        </select>
                                    </div>
                                    
                                    <!-- 分页导航 -->
                                    <nav v-if="pagination.pages > 1" class="mb-2">
                                        <ul class="pagination pagination-sm mb-0">
                                            <!-- 首页 -->
                                            <li class="page-item" :class="{ disabled: pagination.current <= 1 }">
                                                <button class="page-link" 
                                                        @click="changePage(1)" 
                                                        :disabled="pagination.current <= 1"
                                                        title="首页">
                                                    <i class="fas fa-angle-double-left"></i>
                                                </button>
                                            </li>
                                            
                                            <!-- 上一页 -->
                                            <li class="page-item" :class="{ disabled: pagination.current <= 1 }">
                                                <button class="page-link" 
                                                        @click="changePage(pagination.current - 1)" 
                                                        :disabled="pagination.current <= 1"
                                                        title="上一页">
                                                    <i class="fas fa-angle-left"></i>
                                                </button>
                                            </li>
                                            
                                            <!-- 页码 -->
                                            <li class="page-item"
                                                v-for="page in getPageNumbers()"
                                                :key="page"
                                                :class="{ 
                                                    active: page === pagination.current, 
                                                    disabled: page === '...' 
                                                }">
                                                <button class="page-link"
                                                        @click="page !== '...' ? changePage(page) : null"
                                                        :disabled="page === '...'"
                                                        :class="{ 'fw-bold': page === pagination.current }">
                                                    {{ page }}
                                                </button>
                                            </li>
                                            
                                            <!-- 下一页 -->
                                            <li class="page-item" :class="{ disabled: pagination.current >= pagination.pages }">
                                                <button class="page-link" 
                                                        @click="changePage(pagination.current + 1)" 
                                                        :disabled="pagination.current >= pagination.pages"
                                                        title="下一页">
                                                    <i class="fas fa-angle-right"></i>
                                                </button>
                                            </li>
                                            
                                            <!-- 末页 -->
                                            <li class="page-item" :class="{ disabled: pagination.current >= pagination.pages }">
                                                <button class="page-link" 
                                                        @click="changePage(pagination.pages)" 
                                                        :disabled="pagination.current >= pagination.pages"
                                                        title="末页">
                                                    <i class="fas fa-angle-double-right"></i>
                                                </button>
                                            </li>
                                        </ul>
                                    </nav>
                                    
                                    <!-- 当只有一页时显示的信息 -->
                                    <div v-else class="text-muted small mb-2">
                                        <i class="fas fa-check-circle me-1 text-success"></i>
                                        所有数据已显示完毕
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script th:src="@{/webjars/bootstrap/5.3.0/js/bootstrap.bundle.min.js}"></script>

    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    connections: [],
                    searchForm: {
                        username: '',
                        clientIp: '',
                        status: ''
                    },
                    pagination: {
                        current: 1,
                        size: 20,
                        total: 0,
                        pages: 0
                    }
                }
            },
            mounted() {
                this.loadConnections();

                // 每30秒自动刷新
                setInterval(() => {
                    this.loadConnections();
                }, 30000);
            },
            methods: {
                async loadConnections() {
                    try {
                        const params = {
                            page: this.pagination.current,
                            size: this.pagination.size,
                            ...this.searchForm
                        };

                        const response = await axios.get('/api/ftp/connections', { params });
                        if (response.data.code === 200) {
                            this.connections = response.data.records || [];

                            // 处理分页数据 - 兼容不同的响应格式
                            if (response.data.total !== undefined) {
                                this.pagination.total = response.data.total;
                            } else if (response.data.page && response.data.page.total !== undefined) {
                                this.pagination.total = response.data.page.total;
                            } else {
                                this.pagination.total = this.connections.length;
                            }

                            if (response.data.pages !== undefined) {
                                this.pagination.pages = response.data.pages;
                            } else if (response.data.page && response.data.page.totalPage !== undefined) {
                                this.pagination.pages = response.data.page.totalPage;
                            } else {
                                this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.size);
                            }
                        }
                    } catch (error) {
                        console.error('加载连接记录失败:', error);
                        alert('加载连接记录失败');
                    }
                },
                resetSearch() {
                    this.searchForm = { username: '', clientIp: '', status: '' };
                    this.pagination.current = 1;
                    this.loadConnections();
                },
                changePage(page) {
                    if (page >= 1 && page <= this.pagination.pages) {
                        this.pagination.current = page;
                        this.loadConnections();
                    }
                },
                changePageSize() {
                    this.pagination.current = 1;
                    this.loadConnections();
                },
                getPageNumbers() {
                    const pages = [];
                    const total = this.pagination.pages;
                    const current = this.pagination.current;

                    if (total <= 5) {
                        for (let i = 1; i <= total; i++) {
                            pages.push(i);
                        }
                    } else {
                        if (current <= 3) {
                            for (let i = 1; i <= 5; i++) {
                                pages.push(i);
                            }
                            if (total > 5) {
                                pages.push('...');
                                pages.push(total);
                            }
                        } else if (current >= total - 2) {
                            pages.push(1);
                            if (total > 5) {
                                pages.push('...');
                            }
                            for (let i = total - 4; i <= total; i++) {
                                pages.push(i);
                            }
                        } else {
                            pages.push(1);
                            pages.push('...');
                            for (let i = current - 1; i <= current + 1; i++) {
                                pages.push(i);
                            }
                            pages.push('...');
                            pages.push(total);
                        }
                    }

                    return pages;
                },
                formatDate(dateStr) {
                    if (!dateStr) return '-';
                    return new Date(dateStr).toLocaleString('zh-CN');
                },
                formatDuration(seconds) {
                    if (!seconds) return '-';
                    const hours = Math.floor(seconds / 3600);
                    const minutes = Math.floor((seconds % 3600) / 60);
                    const secs = seconds % 60;

                    if (hours > 0) {
                        return `${hours}h ${minutes}m ${secs}s`;
                    } else if (minutes > 0) {
                        return `${minutes}m ${secs}s`;
                    } else {
                        return `${secs}s`;
                    }
                },
                getStatusBadgeClass(status) {
                    switch (status) {
                        case 'CONNECTED': return 'bg-success';
                        case 'DISCONNECTED': return 'bg-secondary';
                        default: return 'bg-secondary';
                    }
                },
                getStatusIcon(status) {
                    switch (status) {
                        case 'CONNECTED': return 'fas fa-plug';
                        case 'DISCONNECTED': return 'fas fa-times-circle';
                        default: return 'fas fa-question-circle';
                    }
                },
                getStatusText(status) {
                    switch (status) {
                        case 'CONNECTED': return '已连接';
                        case 'DISCONNECTED': return '已断开';
                        default: return status;
                    }
                }
            }
        }).mount('#app');
    </script>

    <style>
        /* 分页样式优化 */
        .pagination .page-item.active .page-link {
            background-color: #007bff !important;
            border-color: #007bff !important;
            color: #ffffff !important;
            font-weight: bold;
        }
        
        .pagination .page-item.active .page-link:hover {
            background-color: #0056b3 !important;
            border-color: #0056b3 !important;
            color: #ffffff !important;
        }
        
        .pagination .page-link {
            color: #007bff;
            border: 1px solid #dee2e6;
            padding: 0.375rem 0.75rem;
            margin: 0 2px;
            border-radius: 0.375rem;
            transition: all 0.2s ease-in-out;
        }
        
        .pagination .page-link:hover {
            color: #0056b3;
            background-color: #e9ecef;
            border-color: #dee2e6;
        }
        
        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
        
        .pagination .page-item.disabled .page-link:hover {
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }
        
        /* 分页大小选择器样式 */
        .form-select-sm {
            border-radius: 0.375rem;
            border: 1px solid #ced4da;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .form-select-sm:focus {
            border-color: #86b7fe;
            outline: 0;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
    </style>
</body>
</html>
